package me.khrystal.store.ui.fragment;

import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.TextView;

import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;
import com.lzy.okgo.request.GetRequest;
import com.lzy.okserver.OkDownload;

import java.io.File;
import java.util.ArrayList;

import butterknife.Bind;
import butterknife.OnClick;
import me.khrystal.store.R;
import me.khrystal.store.adapter.SelectAppAdapter;
import me.khrystal.store.base.BaseListFragment;
import me.khrystal.store.base.RecyclerAdapter;
import me.khrystal.store.bean.App;
import me.khrystal.store.bean.CommonResp;
import me.khrystal.store.callback.JsonCallback;
import me.khrystal.store.callback.LogDownloadListener;
import me.khrystal.store.callback.SelectCountCallback;
import me.khrystal.store.http.HttpRequest;
import me.khrystal.store.utils.log.MLog;

/**
 * usage: 快速安装页面 注意 该页面不支持分页加载, 且替换了adapter和布局文件
 * {@link SelectAppAdapter}
 * author: kHRYSTAL
 * create time: 17/7/15
 * update time:
 * email: 723526676@qq.com
 */

public class QuickInstallFragment extends BaseListFragment<App> implements SelectCountCallback {

    private static final String TAG = QuickInstallFragment.class.getSimpleName();
    @Bind(R.id.tvDownload)
    TextView tvDownload;

    @Override
    public int layoutResId() {
        return R.layout.fragment_quick_install;
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
    }

    @Override
    public void loadData(final int page) {
        HttpRequest.getInstance().getQuickInstall(getActivity())
                .execute(new JsonCallback<CommonResp>(CommonResp.class) {
                    @Override
                    public void onSuccess(Response<CommonResp> response) {
                        bindData(response.body(), page == 0);
                    }

                    @Override
                    public void onError(Response<CommonResp> response) {
                        super.onError(response);
                        hideRefreshView();
                        MLog.e(TAG, "请求失败");
                    }
                });
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        // 如果从其他页面详情页下载 则该页面下是否在队列的ui应该刷新
        if (isVisibleToUser && adapter != null) {
            adapter.notifyDataSetChanged();
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        // 进入下载管理清除了下载任务 则该页面下是否在队列的ui应该刷新
        if (adapter != null)
            adapter.notifyDataSetChanged();
    }

    @Override
    protected void addDataToList(CommonResp resp, boolean isRefresh) {
        ((SelectAppAdapter) adapter).updateDataSet(resp.datas);
    }

    @Override
    protected RecyclerAdapter<App> generateAdapter() {
        return new SelectAppAdapter(getActivity(), null, false, this);
    }

    @Override
    protected RecyclerView.LayoutManager generateLayoutManager() {
        return new LinearLayoutManager(getActivity());
    }

    @Override
    public void onSelectCountChanged(int count) {
        tvDownload.setText(String.format("已选择%s项, 点击下载", count));
    }

    @OnClick(R.id.tvDownload)
    public void onClickDownload() {
        ArrayList<App> selectedApp = ((SelectAppAdapter) adapter).getSelectedItem();
        for (App app : selectedApp) {
            // 首先排除已经在下载队列的url
            if (OkDownload.getInstance().getTask(HttpRequest.getDownloadUrl(app.name)) != null) {
                continue; // 跳出本次循环
            }

            GetRequest<File> request = OkGo.<File>get(HttpRequest.getDownloadUrl(app.name));
            // 参数为tag标识和 请求
            OkDownload.request(HttpRequest.getDownloadUrl(app.name), request)
                    .extra1(app)
                    .fileName(app.name + HttpRequest.APK_SUFFIX) // 文件名
                    .save() // 下载状态 进度写入数据库
                    .register(new LogDownloadListener())
                    .start(); // 注册监听

        }
        adapter.notifyDataSetChanged();
    }

}
